/*******************************************************************************
 * Copyright (c) 2009-2011 ETCORE Labs. All rights reserved. 
 * 
 * This software is the confidential and proprietary information of ETCORE Labs.
 * You shall not disclose such confidential information and shall use it
 * only in accordance with the terms of the license agreement you entered into
 * with ETCORE Labs. 
 * 
 * Support can be obtained from support forums at:  http://www.etcore.com/
 * /
 *******************************************************************************/
package etcore.webapp.grouptalk.util;

import java.io.InputStream;
import java.net.URL;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import etcore.webapp.grouptalk.common.object.Mail;

/**
 * MailSender is a utility class used to send a mail
 * 
 * @author ETCORE GroupTalk Developers
 * 
 */
public class MailSender {
	private static Properties properties;

	static {
		properties = new Properties();
		URL url = MailSender.class.getResource("smtp.xml");
		try {
			if (url != null) {
				InputStream is = url.openStream();
				properties.loadFromXML(is);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static final String SMTP_SERVER_HOST = "HOST";

	public static final String SMTP_SERVER_PORT = "PORT";

	public static final String SMTP_SERVER_USER = "USER";

	public static final String SMTP_SERVER_PWD = "PWD";

	public static boolean sendEmail(Mail mail) {
		return sendEmail(properties, mail);
	}

	public static String getFromUser() {
		return properties.getProperty(SMTP_SERVER_USER);
	}

	/**
	 * Send a mail with properties
	 * 
	 * @param smtpProperties
	 *            SMTP properties
	 * @param mail
	 *            mail to be sent
	 * @return
	 */
	public static boolean sendEmail(Properties smtpProperties, Mail mail) {
		if (smtpProperties == null || mail == null)
			return false;
		try {

			Properties props = System.getProperties();
			props.put("mail.smtp.host",
					smtpProperties.getProperty(SMTP_SERVER_HOST));
			props.put("mail.smtp.auth", "true");
			if (smtpProperties.getProperty(SMTP_SERVER_HOST).indexOf("gmail") != -1) {
				// props.put("mail.smtp.starttls.enable", "true");
				props.put("mail.smtp.host", "smtp.gmail.com");
				props.put("mail.smtp.socketFactory.port", "465");
				props.put("mail.smtp.socketFactory.class",
						"javax.net.ssl.SSLSocketFactory");

			}
			props.put("mail.smtp.port",
					smtpProperties.getProperty(SMTP_SERVER_PORT));
			final String user = smtpProperties.getProperty(SMTP_SERVER_USER);
			final String pwd = smtpProperties.getProperty(SMTP_SERVER_PWD);
			Authenticator auth = new Authenticator() {

				public PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication(user, pwd);
				}
			};
			Session mailSession = Session.getInstance(props, auth);
			// Session mailSession = Session.getInstance(props);
			MimeMessage msgs = new MimeMessage(mailSession);
			msgs.setFrom(new InternetAddress(smtpProperties
					.getProperty(SMTP_SERVER_USER)));

			msgs.setSubject(mail.getName(), "utf-8");
			msgs.setHeader("X-Mailer", "smtpsend");
			msgs.setHeader("Content-Type", "text/html; charset=utf-8");
			msgs.setSentDate(new java.util.Date());

			MimeBodyPart mimebodypart = new MimeBodyPart();

			mimebodypart.setContent(mail.getContent(),
					"text/html;charset=utf-8");

			// attach message BODY
			MimeMultipart mimemultipart = new MimeMultipart();
			mimemultipart.addBodyPart(mimebodypart);
			if (mail.getAttachments() != null) {
				// attach FILE
				String[] files = mail.getAttachments().split(";");

				if (files != null) {

					DataSource ds = null;
					for (String file : files) {
						ds = new FileDataSource(file);
						mimebodypart = new MimeBodyPart();
						try {
							mimebodypart.setDataHandler(new DataHandler(ds));
						} catch (Exception exception3) {
							throw exception3;
						}
						mimebodypart.setFileName(ds.getName()); // set FILENAME
						mimemultipart.addBodyPart(mimebodypart);
					}
				}
			}// end if
			msgs.setContent(mimemultipart);

			msgs.setRecipients(Message.RecipientType.TO,
					InternetAddress.parse(mail.getToUsers(), false));
			if (mail.getCcUsers() != null)
				msgs.setRecipients(Message.RecipientType.CC,
						InternetAddress.parse(mail.getCcUsers(), false));
			if (mail.getBccUsers() != null)
				msgs.setRecipients(Message.RecipientType.BCC,
						InternetAddress.parse(mail.getBccUsers(), false));
			Transport transport = mailSession.getTransport("smtp");
			transport.connect(smtpProperties.getProperty(SMTP_SERVER_HOST),
					Integer.parseInt(smtpProperties
							.getProperty(SMTP_SERVER_PORT)), user, pwd);

			Transport.send(msgs);
			transport.close();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

	}

}
